package test.utils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @filename ExecutorUtils
 * @description 线程池工具类
 * @autor 王承
 * @date 2021/6/1 20:19
 */
public class ExecutorUtils {

	static ExecutorService executor = Executors.newFixedThreadPool(8);

	public static void execute(Runnable run) {
		executor.execute(run);
	}

	public static ThreadPoolExecutor getExecutor() {
		return (ThreadPoolExecutor) executor;
	}

	public static void shutdownAndWait() {
		executor.shutdown();
		boolean loop = false;
		do { //等待所有任务完成
			try {
				// 阻塞，直到线程池里所有任务结束
				loop = !executor.awaitTermination(2, TimeUnit.SECONDS);
			} catch (InterruptedException ignored) {
			}
		} while (loop);
	}

}
